package com.my.app.tools.core.service.translate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.my.app.tools.core.service.common.AppConfigService;
import com.my.app.tools.pojo.vo.GlobalResponseEntity;
import com.my.app.tools.pojo.vo.TranslateLangVO;
import com.my.app.tools.util.HttpGet;
import com.my.app.tools.util.LogUtil;

import java.util.List;

public class TranslateYouDaoService extends AbstractTranslateApiService {

    private String translateUrl;

    @Override
    public void reloadAppConfig() {
        translateUrl = AppConfigService.readStringConfig("/app-config/translate-api/youdao/url");
    }

    @Override
    public GlobalResponseEntity<TranslateLangVO[]> translateLang() {
        List<TranslateLangVO> langs = Lists.newArrayList();
        langs.add(new TranslateLangVO("AUTO", "AUTO", "自动识别"));
        return GlobalResponseEntity.success("成功", langs.toArray(new TranslateLangVO[]{}));
    }

    /**
     * 文字翻译
     *
     * @param str
     * @param fromLang
     * @param toLang
     * @return
     * @author guochaohui
     * @date 2020-04-03 16:30
     */
    @Override
    public GlobalResponseEntity<List<String>> translate(String str, String fromLang, String toLang) {
        try {
            String url = String.format(translateUrl, HttpGet.encode(str));
            String result = HttpGet.get(url, null);
            LogUtil.info("translate youdao result: " + result);
            JSONObject jsonObject = JSON.parseObject(result.trim());
            JSONArray transResults = jsonObject.getJSONArray("translateResult");
            List<String> results = Lists.newArrayList();
            for (int i = 0; i < transResults.size(); i++) {
                JSONArray transResult = transResults.getJSONArray(i);
                for (int j = 0; j < transResult.size(); j++) {
                    JSONObject transRes = transResult.getJSONObject(j);
                    results.add(transRes.getString("tgt"));
                }
            }
            return GlobalResponseEntity.success("翻译成功", results);
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.error("translate youdao error: " + e.getMessage());
            return GlobalResponseEntity.failure(e.getMessage());
        }
    }

}
